var $editForm = $("#editForm");
var $modalCountry = $("#modalCountry");
var $modalAreaCode = $("#modalAreaCode");
var $countryContainer = $("#countryContainer");
var $modalBody = $('.js-select-modal');

$editForm.delegate('input[name=countryAreaCode]', 'click', function() {
    $('.list-group-item', $modalAreaCode).addClass('hide');
    $('.js-input', $modalAreaCode).val('');
    $modalAreaCode.modal('show');
})
$editForm.delegate('input[name=nationality]', 'click', function() {
    $('.list-group-item', $modalCountry).addClass('hide');
    $('.js-input', $modalCountry).val('');
    $modalCountry.modal('show');
})


function loadArea() {
    var $listGroup = $('.list-group', $modalAreaCode);
    AREA_CODE.forEach(item => {
        $listGroup.append(`<div class="list-group-item hide" title="${item.toLowerCase()}">${item}</div>`)
    })
}

function loadCountry() {
    var $listGroup = $('.list-group', $modalCountry);
    COUNTRY.forEach(item => {
        $listGroup.append(`<div class="list-group-item hide" title="${item.toLowerCase()}">${item}</div>`)
    })
}

$modalBody.delegate('.js-input', 'keyup', function() {
    var $modal = $(this).parents('.js-select-modal');
    var text = $.trim($(this).val()).toLowerCase();
    var $listGroup = $('.list-group-item', $modal);
    if (text.length < 1) {
        $listGroup.addClass('hide');
        return false;
    }
    $listGroup.each(function() {
        var title = $(this).attr('title');
        if (title.indexOf(text) >= 0) {
            $(this).removeClass('hide');
        } else {
            $(this).addClass('hide');
        }
    })
})

$modalBody.delegate('.list-group-item', 'click', function() {
    var $modal = $(this).parents('.js-select-modal');
    var text = $(this).text();
    var $input = $('.js-input', $modal);
    var name = $input.attr('name');
    $(`input[name=${name}]`, $editForm).val(text);
    $modal.modal('hide');
})

$modalBody.delegate('.js-submit', 'click', function() {
    var $modal = $(this).parents('.js-select-modal');
    var $input = $('.js-input', $modal);
    var text = $.trim($input.val());
    if (text.length > 0) {
        var name = $input.attr('name');
        $(`input[name=${name}]`, $editForm).val(text);
        $modal.modal('hide');
    }
})

$(document).ready(function() {
    loadArea();
    loadCountry();
})